package chenxi.guava;

import com.google.common.util.concurrent.RateLimiter;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * @author bowen
 */
public class RateLimiterDemo {

//    static


    public static void main(String[] args) throws InterruptedException {
        List<Runnable> tasks = new ArrayList<Runnable>();
        for(int i = 0;i < 4000; i++){
            tasks.add(new UserRequest(i));
        }

//        acquire(tasks);
        tryAcquire(tasks);
    }

//    private static void acquire(List<Runnable> tasks) {
//        ExecutorService threadPool = Executors.newCachedThreadPool();
//        for (Runnable runnable : tasks){
//            System.out.println("等待时间：" + rateLimiter.acquire());
//            threadPool.execute(runnable);
//        }
//        threadPool.shutdown();
//    }

    private static void tryAcquire(List<Runnable> tasks) throws InterruptedException {
        RateLimiter rateLimiter = RateLimiter.create(1000);
//        Thread.sleep(20000L);
        ExecutorService threadPool = Executors.newCachedThreadPool();
        for (Runnable runnable : tasks){
            if (rateLimiter.tryAcquire(2,TimeUnit.MILLISECONDS)) {
                threadPool.execute(runnable);
            }
        }
        threadPool.shutdown();

    }

    private static class UserRequest implements Runnable {
        private int id;

        public UserRequest(int id) {
            this.id = id;
        }

        @Override
        public void run() {
            System.out.println(id);
        }
    }


}
